LINQ to XML - Write Samples


LINQ, LINQ to XML, .NET Framework 4.0
LINQ, LINQ to XML, XML, Console Window, XML Documentation
Desktop, Data
en-US
6/28/2011

Introduction

These samples demonstrate how to use XmlWriter to output XML data.

Building the Sample

  1. Open Program.cs
  2. Uncomment the line for the sample that you want to run; comment ones you don't want to run
  3. Press Ctrl + F5

Screenshot

Sample Code

C#
Edit|Remove
            [Category("Write")] 
            [Description("Write an XElement to XmlWriter using the WriteTo method")] 
            public void XLinq15() 
            { 
                XElement po1 = new XElement("PurchaseOrder", 
                                new XElement("Item", "Motor", 
                                  new XAttribute("price", "100"))); 
 
                XElement po2 = new XElement("PurchaseOrder", 
                                new XElement("Item", "Cable", 
                                  new XAttribute("price", "10"))); 
 
                XElement po3 = new XElement("PurchaseOrder", 
                                new XElement("Item", "Switch", 
                                  new XAttribute("price", "10"))); 
 
                StringWriter sw = new StringWriter(); 
                XmlWriterSettings settings = new XmlWriterSettings(); 
                settings.Indent = true; 
                XmlWriter w = XmlWriter.Create(sw, settings); 
                w.WriteStartElement("PurchaseOrders"); 
 
                po1.WriteTo(w); 
                po2.WriteTo(w); 
                po3.WriteTo(w); 
 
                w.WriteEndElement(); 
                w.Close(); 
                Console.WriteLine(sw.ToString()); 
            }

Source Code Files

More Information

For more information on LINQ to XML: